package com.peking.donations.web.controller;

import com.alibaba.druid.util.StringUtils;
import com.google.common.collect.Maps;
import com.peking.donations.base.security.LoggedUser;
import com.peking.donations.base.util.DigitalUtil;
import com.peking.donations.base.util.SecurityUtil;
import com.peking.donations.base.vo.AjaxResponse;
import com.peking.donations.model.DonationSaving;
import com.peking.donations.model.DonationUser;
import com.peking.donations.plugins.pay.wx.service.AuthorizeService;
import com.peking.donations.plugins.pay.wx.utils.GlobalConfigure;
import com.peking.donations.plugins.pay.wx.utils.WxpayException;
import com.peking.donations.service.BizService;
import com.peking.donations.service.UserService;
import com.peking.donations.vo.GiftCallVo;
import com.peking.donations.vo.GradeVo;
import com.peking.donations.vo.PayVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * Created by wyz on 16/4/27.
 */
@Controller
@RequestMapping("/peking")
public class DonationController {

    @Autowired
    AuthorizeService authorizeService;

    @Autowired
    BizService bizService;

    @Autowired
    UserService userService;

    @Autowired
    CacheManager cacheManager;

    @Autowired
    GlobalConfigure globalConfigure;

    @Value("${global.encryptkey}")
    private String encryptkey;

    private static Map<String, String> map = Maps.newHashMap();

    Logger logger= LoggerFactory.getLogger(getClass());

    /**
     * 首页
     *
     * @return
     */
    @RequestMapping(name = "index", value = "/index", method = RequestMethod.GET)
    public String forwardIndex() {
        return "index";
    }

    /**
     * 刷新token
     */
    @RequestMapping(name = "refreshToken", value = "/refreshToken", method = RequestMethod.GET)
    public void token() {
        try {
            authorizeService.refreshAccessToken();
            authorizeService.refreshJSTicket();
        } catch (WxpayException e) {
            e.printStackTrace();
        }

    }

    /**
     * 活动介绍页
     *
     * @param modelMap
     * @return
     */
    @RequestMapping(name = "description", value = "/description", method = RequestMethod.GET)
    public String forwardDescription(ModelMap modelMap) {
        Map<String, Integer> totalCountMap = bizService.countTotal();
        modelMap.put("totalCountMap", totalCountMap);
        return "description";
    }

    /**
     * 个人红包页
     *
     * @return
     */
    @RequestMapping(name = "gift", value = "/gift", method = RequestMethod.GET)
    public String gift(ModelMap modelMap) {
        DonationUser user = userService.findByOpenId(SecurityUtil.getCurrentUser().getOpenId());
        modelMap.put("user", user);
        return "gift";
    }

    @RequestMapping(value = "/pay", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public AjaxResponse pay(@RequestBody PayVo payVo) {
        LoggedUser currentUser = SecurityUtil.getCurrentUser();
        DonationSaving saving = new DonationSaving();
        try {
            saving.setType(payVo.getType());
            saving.setRealName(payVo.getRealName());
            saving.setShare(payVo.getShare());
            saving.setAmount(new Long(DigitalUtil.yuan2fen(payVo.getAmount())).intValue());
            saving.setOpenId(currentUser.getOpenId());
            saving.setUserId(currentUser.getUserId());
            saving.setOrderId(payVo.getCallId());
            saving = bizService.createDonationSaving(saving);

            logger.debug("pay post data {}",payVo);
            DonationUser user = userService.findByOpenId(currentUser.getOpenId());
            user.setType(payVo.getuType());
            user.setRealName(payVo.getRealName());
            userService.updateUser(user);
        } catch (Exception e) {
            return AjaxResponse.ERROR("SAVING_ERROR");
        }

        return AjaxResponse.OK(saving);
    }

    /**
     * 填写院系信息
     *
     * @return
     */
    @RequestMapping(name = "success", value = "/pay/success", method = RequestMethod.GET)
    public String success(@RequestParam String callId, ModelMap modelMap) {
        LoggedUser currentUser = SecurityUtil.getCurrentUser();
        DonationUser user = userService.findByOpenId(currentUser.getOpenId());
        if (user.getType() != DonationUser.TYPE_BDZY && StringUtils.isEmpty(user.getGrade())) {
            modelMap.addAttribute("callId", callId);
            return "paySuccess";
        }
        return "redirect:/peking/thanks?callId=" + callId;
    }

    @RequestMapping(name = "saving", value = "/user/saving", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public AjaxResponse userSaving(@RequestBody GradeVo vo) {
        LoggedUser currentUser = SecurityUtil.getCurrentUser();

        userService.updateUser(currentUser.getUserId(), vo.getGrade(), vo.getDepartment(),
                this.getDepartmentCode(vo.getDepartment()));
        return AjaxResponse.OK("" + vo.getCallId());
    }

    /**
     * 感谢支持
     *
     * @return
     */
    @RequestMapping(name = "thanks", value = "/thanks", method = RequestMethod.GET)
    public String thanks(ModelMap modelMap, @RequestParam String callId) {
        LoggedUser user = SecurityUtil.getCurrentUser();
        Map<String, Integer> totalCountMap = bizService.countTotal();
        modelMap.put("totalCountMap", totalCountMap);
        Map<String, Integer> gradeCountMap = bizService.findDepartmentOrder(user.getUserId());
        modelMap.put("gradeCountMap", gradeCountMap);
        GiftCallVo order = new GiftCallVo();
        if (!StringUtils.isEmpty(callId)) {
            order = bizService.getGiftCall(Integer.valueOf(callId));
        }
        modelMap.put("callId", callId);
        modelMap.put("globalHostName", globalConfigure.getHostname());
        DonationUser donationUser = userService.findByOpenId(user.getOpenId());
        modelMap.put("user", donationUser);
        modelMap.put("callOrder", order);
        return "thanks";
    }

    /**
     * 分享页面
     *
     * @param modelMap
     * @return
     */
    @RequestMapping(name = "share", value = "/share", method = RequestMethod.GET)
    public String share(ModelMap modelMap) {
        return "thanks";
    }

    private String getDepartmentCode(String department) {
        String[] ss = { "001_数学科学学院", "002_物理学院", "003_信息科学技术学院", "004_化学与分子工程学院", "005_生命科学学院", "006_地球与空间科学学院",
                "007_城市与环境学院", "008_环境科学与工程学院", "009_心理学系", "010_中国语言文学系", "011_历史学系", "012_考古文博学院", "013_哲学系",
                "014_宗教学系", "015_国际关系学院", "016_经济学院", "017_法学院", "018_信息管理系", "019_社会学系", "020_政府管理学院", "021_外国语学院",
                "022_继续教育学院", "023_艺术学院", "024_中国经济研究中心", "025_教育学院", "026_医学部", "027_马克思主义学院", "028_光华管理学院",
                "029_对外汉语教育学院", "030_软件与微电子学院", "031_新闻传播学院", "032_工学院", "033_元培学院", "034_北大深圳研究生院", "035_环境学院",
                "036_元培计划委员会", "037_艺术系", "038_力学与工程科学系", "039_软件学院", "040_电子学系", "041_计算机科学技术系", "042_城市与环境学系",
                "043_环境科学中心", "044_考古文博院", "045_信息科学中心", "046_人口研究所", "047_汉语中心（对外汉语教学中心）", "048_物理学系", "049_地球物理学系",
                "050_技术物理系", "051_地质学系", "052_政治学与行政管理系", "053_遥感技术与应用研究所（遥感与地理信息系统研究所）", "054_高等教育研究所", "055_考古系",
                "056_法律学系", "057_知识产权学院", "058_东方学系", "059_西方语言文学系", "060_俄罗斯语言文学系", "061_英语语言文学系", "062_南亚东南亚研究所",
                "063_应用文理学院", "064_数学系", "065_概率统计系", "066_力学系", "067_无线电电子学系", "068_国际政治系", "069_亚非研究所", "070_化学系",
                "071_工商管理学院", "072_汉语中心", "073_遥感技术与应用研究所", "074_中国革命与建设中心", "075_社会发展研究所", "076_生物学系", "077_管理科学中心",
                "078_图书馆学与情报学系", "079_东方学语言文学系", "080_马列主义研究所", "081_地理学系", "082_社会学", "083_图书馆学情报学系", "084_东方语言文学系",
                "085_政治学与行政管理学系", "086_环境科学研究中心", "087_管理科学中心（经济学）", "088_遥感技术应用研究所", "089_科学与社会研究中心",
                "090_中国革命与建设中心（经济学）", "091_科学管理中心（经济学）", "092_遥感中心", "093_图书馆学系", "094_遥感研究所", "095_计算机系", "096_中文系",
                "097_英语系", "098_西语系", "099_考古学系", "100_地球物理系", "101_外国哲学研究所", "102_马列教研室", "103_经济学系", "104_法律系",
                "105_中国革命与建设研究中心", "106_地质地理系", "107_夜大计算机软件工程专修科", "108_物理系", "109_地质系", "110_地理系", "111_历史系",
                "112_经济系", "113_东语系", "114_俄语系", "115_生物系", "116_无线电系", "117_图书馆系", "118_技术物理系（汉中分校）", "119_无线电系（汉中分校）",
                "120_电子仪器系", "121_国际政治", "122_图书馆学", "123_公共英语系", "124_出处", "125_院/系", "126_数学力学系", "127_制药厂",
                "128_电子仪器厂", "129_力学系（汉中分校）", "130_无线电电子学系（汉中分校）", "131_政治经济系", "132_俄语言文学系", "133_政治系", "134_研究生",
                "135_物理", "136_化学", "137_生物", "138_历史", "139_中文", "140_东语", "141_原子能系046~4", "142_地质地理学系", "143_原子能系",
                "144_图书馆专修科", "145_数研三", "146_物研三", "147_化研三", "148_生研三", "149_中研三", "150_史研三", "151_政经研三",
                "152_马列主义基础教研室", "153_数学专修科", "154_气象专修科", "155_图书馆", "156_语言专修科", "157_生物系 ", "158_英语系 ", "159_经济系 ",
                "160_物理系 ", "161_化学系 ", "162_图书馆学科", "163_数学研究部", "164_物理学研究部", "165_生物研究部", "166_理学院数学系",
                "167_理学院物理学系", "168_理学院化学系", "169_理学院植物系", "170_理学院动物系", "171_理学院地质系", "172_工学院机械工程系", "173_工学院电机工程系",
                "174_工学院化学工程系", "175_工学院土木工程系", "176_工学院建筑工程系", "177_工学院农田水利专修科", "178_地质专修科", "179_工学院发电工程专修科",
                "180_法学院法律学系", "181_法学院政治学系", "182_法学院经济学系", "183_文学院中国语文学系", "184_文学院史学系", "185_文学院哲学系",
                "186_文学院西方语文学系", "187_文学院东方语文学系", "188_文学院俄语系", "189_文学院图书馆学系", "190_文学院东方语文学专修科", "191_文学院博物馆专修科",
                "192_工 电机研究所", "193_理 数学研究所", "194_文 哲学研究所", "195_文 史学研究所", "196_文 中语研究所", "197_文 西语研究所", "198_法 法律研究所",
                "199_法 政治研究所", "200_理 化学研究所", "201_理 动物研究所", "202_动物学研究部", "203_史学研究部", "204_文学院图书馆专修科", "205_医学院",
                "206_理学数学研究所", "207_化学研究所", "208_植物研究所", "209_西语研究所", "210_理学院动物学系", "211_文学院教育学系", "212_医学院医学系",
                "213_医学院医学院药学", "214_医学院牙学", "215_农学院农艺系", "216_农学院园艺系", "217_农学院昆虫系", "218_农学院植病学系", "219_农学院森林系",
                "220_农学院农化", "221_农学院土壤肥料", "222_农学院畜牧", "223_农学院兽医", "224_农学院农经", "225_理学院植物研究所", "226_法学院法律研究所" };
        if (CollectionUtils.isEmpty(map)) {
            for (int i = 0; i < ss.length; i++) {
                map.put(ss[i].split("_")[1], ss[i].split("_")[0]);
            }
        }
        return map.get(department);
    }
}
